package org.hot100_5.leetcode102;

import org.leetcode.TreeNode;

import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;

public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {

        return method(root);
    }

    private List<List<Integer>> method(TreeNode root){
        if (root==null){
            return null;
        }
        List<List<Integer>> res = new ArrayList<>();
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.add(root);

        while (!deque.isEmpty()){
            int size = deque.size();
            List<Integer> item = new ArrayList<>();
            while (size>0){
                TreeNode node = deque.poll();
                size--;
                item.add(node.val);
                if (node.left!=null) deque.add(node.left);
                if (node.right!=null) deque.add(node.right);
            }
            res.add(item);
        }

        return res;
    }

}
